package com.gdkj.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.gdkj.common.BussCommonResponse;
import com.gdkj.common.LogicResult;
import com.gdkj.ip.IIp;
import com.gdkj.util.IPUtils;
import com.gdkj.util.StringUtils;
import com.xjgks.common.constant.HttpResultConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ip和设备黑名单
 */
@Component
@Slf4j
public class IpDeviceInterceptor implements HandlerInterceptor {

    @Autowired
    private IIp ipService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String deviceIdOne = request.getHeader("device_id");
        String deviceIdTwo = request.getHeader("device-id");
        String ip = IPUtils.getIpAddr(request);

        // 设置请求Ip
        if(StringUtils.isNotEmpty(ip)){
            request.setAttribute("ip", ip);
        }

        // 检查用户白名单
        String jwtToken = request.getHeader("Authorization");
        if (StrUtil.isNotEmpty(jwtToken)) {
            Long uid = (Long) request.getAttribute("uid");
            if (uid != null && ipService.checkUserWhite(uid)) {
                return true;
            }
        } else {
            // token未传默认返回成功
            return true;
        }

        LogicResult authIpAndDeviceResult = ipService.authIpAndDevice(ip, deviceIdOne, deviceIdTwo);
//        log.info("客户端获取到的ip地址为:" + ip);
        if (!HttpResultConstants.SUCCESS_CODE.equals(authIpAndDeviceResult.getCode())) {
            BussCommonResponse.print(response, LogicResult.buildResult(authIpAndDeviceResult));
            return false;
        }
        return true;
    }
}
